import string

from django.core.files.storage import FileSystemStorage
from django.shortcuts import render, redirect, reverse
from django.http.response import JsonResponse, HttpResponseRedirect
import string
import random
from django.core.mail import send_mail
from .models import CaptchaModel
from django.views.decorators.http import require_http_methods
from .forms import RegisterForm, LoginForm
from django.contrib.auth import get_user_model, login, logout

# from django.contrib.auth.models import User
User = get_user_model()


# Create your views here.
@require_http_methods(['GET', 'POST'])
def login0(request):
    if request.method == 'GET':

        return render(request, template_name='4.login.html')
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            password = form.cleaned_data.get('password')
            remember = form.cleaned_data.get('remember')
            # 把密码加密存储
            user = User.objects.filter(email=email).first()
            if user and user.check_password(password):
                # 登录
                login(request, user)
                user.is_authenticated
                # 没有点击就设置过期时间为0，关闭浏览器就过期
                if not remember:
                    request.session.set_expiry(0)
                # 点击了就默认两周
                return redirect('/')
            else:
                print('邮箱或者密码错误')
                return redirect(reverse('auth0:login'))
        else:
            error = form.errors
            return redirect(reverse('auth0:login'))


def logout0(request):
    logout(request)
    return redirect('/')


@require_http_methods(['GET', 'POST'])
def register(request):
    if request.method == 'GET':
        return render(request, template_name='5.register.html')
    else:
        form = RegisterForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            # 把密码加密存储
            User.objects.create_user(email=email, username=username, password=password)
            return redirect(reverse('auth0:login'))
        else:
            print(form.errors)
            # 重新跳转到注册界面
            return redirect(reverse('auth0:register'))


def send_email(request):
    email = request.GET.get('email')
    if not email:
        return JsonResponse({'code': 400, 'message': '必须传递邮箱'})
    captcha = "".join(random.sample(string.digits, 6))
    CaptchaModel.objects.update_or_create(email=email, defaults={'captcha': captcha})
    send_mail('猜不猜不猜验证码', message=f'您注册的验证码是:{captcha},验证码五分钟内有效。', recipient_list={email},
              from_email=None)
    return JsonResponse({'code': 200, 'message': '验证码发送成功'})


from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from blog.models import User
from django.conf import settings
import os


@login_required
def user_profile(request):
    if request.method == 'POST':
        # 更新用户信息
        user = request.user
        user.email = request.POST.get('email', user.email)
        user.nickname = request.POST.get('nickname', user.nickname)
        user.age = request.POST.get('age', user.age)
        user.birthday = request.POST.get('birthday', user.birthday)
        user.gender = request.POST.get('gender', user.gender)
        user.save()
        return redirect('auth0:user_profile')

    gender_choices = User.gender_choices
    return render(request, '6.user_profile.html', {
        'gender_choices': gender_choices
    })


@login_required
def update_avatar(request):
    if request.method == 'POST' and request.FILES.get('image'):
        user = request.user
        uploaded_file = request.FILES['image']

        # 确保 upload 目录存在
        upload_dir = os.path.join(settings.MEDIA_ROOT, 'upload')
        os.makedirs(upload_dir, exist_ok=True)

        # 删除旧头像
        if user.image:
            old_image_path = os.path.join(settings.MEDIA_ROOT, str(user.image))
            if os.path.exists(old_image_path):
                os.remove(old_image_path)

        # 使用 FileSystemStorage 保存文件到 upload 目录
        fs = FileSystemStorage(location=upload_dir)
        filename = fs.save(f"user_{user.id}_{uploaded_file.name}", uploaded_file)

        # 更新用户头像字段
        user.image.name = os.path.join('upload', filename)
        user.save()

        return JsonResponse({
            'success': True,
            'avatar_url': user.image.url
        })

        # 错误处理
    if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
        return JsonResponse({
            'success': False,
            'message': '无效的请求'
        })
    return HttpResponseRedirect(reverse('/'))
